﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Text;
using System.Net;
using System.Security.Cryptography;

namespace LingDingSoft2
{
    public partial class yourpage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ////跳转过来的授权信息
            //if (Request.QueryString.AllKeys.Contains("code"))
            //{
            //    //从你的数据库中获取你的token信息
            //    Model.TokenModel token = AppConfig.GetToken();
            //    if (token == null)
            //    {
            //        //数据库中没有找到你的token信息，请求获取
            //        Service.AccessTokenService tokenSvc = new Service.AccessTokenService();
            //        var vRtsToken = tokenSvc.GetToken(Request.QueryString["code"]);
            //        if (vRtsToken != null)
            //        {
            //            //保存你的token信息到数据库
            //        }
            //        else
            //        {
            //            //token信息获取失败的操作
            //        }
            //    }
            //    else
            //    {
            //        //
            //    }




            //}
            //else
            //if (Request.QueryString.AllKeys.Contains("error"))
            //{
            //    //拒绝授权
            //    //拒绝描述 Request.QueryString.AllKeys.Contains("error_description") 
            //}
            //else
            //{
            //    //这里接收饿了么推送的过来的信息
            //}
        }
    }

    /// <summary>
    /// 配置文件获取操作
    /// </summary>
    public class AppConfig
    {
        public static string GetSecret()
        {
            string rRts = "c3a6eeb79750f79f73c7a0722568ffbeccfabf18";
            return rRts;
        }
        public static string GetAppKey()
        {
            string rRts = "fkH9ANkaLB";
            return rRts;
        }
        public static Encoding GetEncoding()
        {

            return Encoding.UTF8;
        }
        public static string GetAPIUrl()
        {
            return "https://open-api-sandbox.shop.ele.me/api/v1/";
        }
        public static string GetTokenUrl()
        {
            return "https://open-api-sandbox.shop.ele.me/token";
        }
        public static string GetCallBackUrl()
        {
            return "http://ceshi.chineseu.cn/callback";
        }
        /// <summary>
        /// 获取Token注意处理过期问题
        /// </summary>
        /// <returns></returns>
        public static Model.TokenModel GetToken()
        {
            Model.TokenModel token = null;
            string jsonPath = "";

            //以下是从文件中获取，实际运用时需要换成数据库
            if (HttpContext.Current != null)
            {
                jsonPath = HttpContext.Current.Server.MapPath("tokenjson.txt");

            }
            else
            {
                jsonPath = AppDomain.CurrentDomain.BaseDirectory + "tokenjson.txt";
            }
            if (System.IO.File.Exists(jsonPath))
            {
                var json = System.IO.File.ReadAllText(jsonPath);
                if (!string.IsNullOrEmpty(json))
                {
                    token = Newtonsoft.Json.JsonConvert.DeserializeObject<Model.TokenModel>(json);
                }
            }




            if (token == null)
            {
                throw new NullReferenceException("未找到Token信息");
            }

            //以下自行处理
            //判断是否过期   前一次获取的时间  + new TimeSpan(0,0, token.expires_in) <当前时间
            if (false)
            {
                //刷新你的token
                Service.AccessTokenService Svc = new Service.AccessTokenService();
                var refToken = Svc.GetRefreshToken(token.refresh_token);
                if (refToken != null)
                {
                    //保存你的token
                    token = refToken;
                }
                else
                {
                    //异常处理
                }

            }


            return token;
        }

    }

    public class SignatureCreater
    {
        private Dictionary<string, object> _params;
        private Parameter.RequestMetas _metas;
        private string _action;
        private string _token;
        private string _secret;
        public SignatureCreater(Dictionary<string, object> Params, Parameter.RequestMetas metas, string action, string token, string secret)
        {
            _action = action;
            _token = token;
            _secret = secret;
            _params = Params;
            _metas = metas;
        }
        public string GetResult()
        {
            StringBuilder rRts = new StringBuilder();
            string vRts = string.Empty;
            List<string> nl = new List<string>();
            if (_params != null)
            {
                foreach (var item in _params)
                {

                    nl.Add(string.Format("{0}={1}", item.Key, Newtonsoft.Json.JsonConvert.SerializeObject(item.Value)));
                }
            }

            nl.Add(string.Format("{0}=\"{1}\"", "app_key", _metas.app_key));
            nl.Add(string.Format("{0}={1}", "timestamp", _metas.timestamp));

            nl.Sort();
            foreach (var item in nl)
            {
                vRts += item;
            }
            vRts = _action + _token + vRts + _secret;

            MD5 md5 = new MD5CryptoServiceProvider();
            var vRtsMd5 = md5.ComputeHash(Encoding.UTF8.GetBytes(vRts));


            foreach (var item in vRtsMd5)
            {
                rRts.Append(item.ToString("X"));
            }

            return rRts.ToString();
        }
    }

    namespace Service
    {

        public class ServiceBase
        {
            public string SendRequest(string id, string action, Dictionary<string, object> Params)
            {
                if (Params == null)
                {
                    Params = new Dictionary<string, object>();
                }
                var token = AppConfig.GetToken();
                if (token==null)
                {
                    throw  new  Exception("Token未获取到");
                }

                Parameter.RequestParameter model = new Parameter.RequestParameter();
                model.action = action;
                model.id = id;
                model.metas = new Parameter.RequestMetas() { app_key = AppConfig.GetAppKey(), timestamp = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds };
                model.token = token.access_token;
                model.Params = Params;
                model.signature = new SignatureCreater(model.Params, model.metas, model.action, model.token, AppConfig.GetSecret()).GetResult();


                var helper = new Http.HttpRequestHelper();
                return helper.SendRequest(AppConfig.GetAPIUrl(), new Http.JsonBodyWriter(Newtonsoft.Json.JsonConvert.SerializeObject(model)));
            }
            /// <summary>
            /// 返回结果，出错则返回null;
            /// </summary>
            /// <param name="action"></param>
            /// <param name="Params"></param>
            /// <returns></returns>
            public T SendRequestEx<T>(string action, Dictionary<string, object> Params)
            {
                string id = System.Guid.NewGuid().ToString();
                var vRts = SendRequest(id, action, Params);
                var model = Newtonsoft.Json.JsonConvert.DeserializeObject<Model.ResponseModel<T>>(vRts);
                if (model != null)
                {
                    if (id != model.id)
                    {
                        //非法交互 自行处理
                        return default(T);
                    }
                    //没有错误时，返回得到的请求对象
                    if (model.error == null)
                    {
                        return model.result;
                    }
                    else
                    {
                        //处理异常
                    }
                }
                return default(T);

            }
        }
        /// <summary>
        /// Token获取
        /// </summary>
        public class AccessTokenService
        {

            public AccessTokenService()
            {

            }
            public Model.TokenModel GetToken(string code)
            {
                try
                {
                    Parameter.AccessTokenParameter model = new Parameter.AccessTokenParameter();
                    model.client_id = AppConfig.GetAppKey();
                    model.code = code;
                    model.grant_type = "authorization_code";
                    model.redirect_uri = AppConfig.GetCallBackUrl();


                    var vParams = new Dictionary<string, string>();
                    var vHeader = new Dictionary<string, string>();

                    vParams.Add("client_id", HttpUtility.UrlEncode(model.client_id));
                    vParams.Add("code", HttpUtility.UrlEncode(model.code));
                    vParams.Add("redirect_uri", HttpUtility.UrlEncode(model.redirect_uri));
                    vParams.Add("grant_type", HttpUtility.UrlEncode(model.grant_type));

                    vHeader.Add("Authorization", _GetAuthorizationValue(AppConfig.GetAppKey() + ":" + AppConfig.GetSecret()));

                    var helper = new Http.HttpRequestHelper();
                    var vRts = helper.SendRequest(AppConfig.GetTokenUrl(), new Http.ApplicationBodyWriter(vParams), vHeader);
                    return Newtonsoft.Json.JsonConvert.DeserializeObject<Model.TokenModel>(vRts);
                }
                catch (Exception ex)
                {
                    //异常处理

                    return null;
                }

            }
            /// <summary>
            /// Token
            /// </summary>
            /// <returns></returns>
            public Model.TokenModel GetRefreshToken(string refreshToken)
            {
                try
                {
                    Parameter.RefreshTokenParameter model = new Parameter.RefreshTokenParameter();
                    model.grant_type = "refresh_token";
                    model.refresh_token = refreshToken;

                    var vParams = new Dictionary<string, string>();
                    var vHeader = new Dictionary<string, string>();

                    vParams.Add("refresh_token", HttpUtility.UrlEncode(model.refresh_token));
                    vParams.Add("grant_type", HttpUtility.UrlEncode(model.grant_type));

                    vHeader.Add("Authorization", _GetAuthorizationValue(AppConfig.GetAppKey() + ":" + AppConfig.GetSecret()));

                    var helper = new Http.HttpRequestHelper();
                    var vRts = helper.SendRequest(AppConfig.GetTokenUrl(), new Http.ApplicationBodyWriter(vParams), vHeader);
                    return Newtonsoft.Json.JsonConvert.DeserializeObject<Model.TokenModel>(vRts);
                }
                catch (Exception ex)
                {
                    //异常处理

                    return null;
                }

            }
            private string _GetAuthorizationValue(string str)
            {
                byte[] bytes = Encoding.Default.GetBytes(str);
                string rRts = string.Empty;
                rRts = "Basic " + Convert.ToBase64String(bytes);
                return rRts;
            }

        }

        public class UserService : ServiceBase
        {
            public UserService()
            {


            }
            public Model.UserModel GetUserInfo()
            {

                var vRts = SendRequestEx<Model.UserModel>("eleme.user.getUser", null);

                return vRts;
            }
        }
        public class ShopService : ServiceBase
        {
            private long _shopID;
            private Dictionary<string, object> _Params;

            public ShopService(long userID)
            {
                _shopID = userID;
                _Params = new Dictionary<string, object>();
                _Params.Add("shopId", _shopID);
            }
            public List<Model.ShopCateModel> GetShopCate()
            {
                return SendRequestEx<List<Model.ShopCateModel>>("eleme.product.category.getShopCategories", _Params);

            }

            public List<Model.ShopCateModel> GetShopCateWithChildren()
            {
                return SendRequestEx<List<Model.ShopCateModel>>("eleme.product.category.getShopCategoriesWithChildren", _Params);

            }
            /// <summary>
            /// 带参示例
            /// </summary>
            /// <param name="exampleParams"></param>
            /// <returns></returns>
            public List<Model.ShopCateModel> GetExample(string exampleParams)
            {
                _Params.Add("exampleParamsName", exampleParams);
                return SendRequestEx<List<Model.ShopCateModel>>("eleme.product.category.getShopCategoriesWithChildren", _Params);

            }

        }
    }

    namespace Parameter
    {
        public class AccessTokenParameter
        {
            public string grant_type { get; set; }
            public string code { get; set; }
            public string redirect_uri { get; set; }
            public string client_id { get; set; }
        }
        public class RefreshTokenParameter
        {
            public string grant_type { get; set; }
            public string refresh_token { get; set; }

        }

        public class RequestParameter
        {
            public string token { get; set; }
            public string nop { get { return "1.0.0"; } }
            public RequestMetas metas { get; set; }
            [Newtonsoft.Json.JsonProperty("params")]
            public Dictionary<string, object> Params { get; set; }
            public string action { get; set; }
            public string id { get; set; }
            public string signature { get; set; }
        }
        public class RequestMetas
        {
            public string app_key { get; set; }
            public long timestamp { get; set; }
        }

    }


    namespace Model
    {
        public class ResponseModel<T>
        {
            public string nop { get; set; }
            public string id { get; set; }
            public T result { get; set; }
            public ErrorModel error { get; set; }
        }
        public class ErrorModel
        {
            public string code { get; set; }
            public string message { get; set; }
        }
        public class ShopCateModel
        {
            public string id { get; set; }
            public string name { get; set; }
            public string description { get; set; }
            public string isValid { get; set; }
            public string parentId { get; set; }
            //没有对应的数据 对象
            //public List<Children> children { get; set; }

        }
        public class TokenModel
        {
            public string access_token { get; set; }
            public string token_type { get; set; }
            public int expires_in { get; set; }
            public string refresh_token { get; set; }
            public string scope { get; set; }

        }
        public class AuthorizedShops
        {
            public long id { get; set; }
            public string name { get; set; }
        }

        public class UserModel
        {
            public long userId { get; set; }
            public string userName { get; set; }
            public List<AuthorizedShops> authorizedShops { get; set; }
        }
    }

    namespace Http
    {
        public class ApplicationBodyWriter : IBodyWriter
        {
            private ICollection<KeyValuePair<string, string>> _requestParams;
            private Encoding _coding;
            public ApplicationBodyWriter(ICollection<KeyValuePair<string, string>> requestParams, Encoding coding)
            {
                _requestParams = requestParams;
                _coding = coding;

            }
            public ApplicationBodyWriter(ICollection<KeyValuePair<string, string>> requestParams)
            {
                _requestParams = requestParams;
                _coding = AppConfig.GetEncoding();

            }
            public void Writer(HttpWebRequest request)
            {

                request.ContentType = "application/x-www-form-urlencoded";

                var strBuf = new StringBuilder();
                if (_requestParams != null)
                {
                    foreach (var item in _requestParams)
                    {
                        strBuf.Append(string.Format("&{0}={1}", item.Key, item.Value));
                    }
                    if (strBuf.Length > 0)
                    {
                        strBuf.Remove(0, 1);
                    }
                }

                request.Method = "post";
                var requestStream = request.GetRequestStream();
                var tempBuffer = _coding.GetBytes(strBuf.ToString());
                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();

            }
        }
        public class HttpRequestHelper
        {
            //public string SendRequest(string url, ICollection<KeyValuePair<string, string>> requestParams)
            //{
            //    Encoding coding = AppConfig.GetEncoding();
            //    return SendRequest(url, new MultipartBodyWriter(requestParams, coding), coding);
            //}
            //public string SendRequest(string url, ICollection<KeyValuePair<string, string>> requestParams, Encoding encoding)
            //{
            //    return SendRequest(url, new MultipartBodyWriter(requestParams, encoding), encoding);
            //}
            //public string SendRequest(string url, ICollection<KeyValuePair<string, string>> requestParams, ICollection<KeyValuePair<string, string>> header)
            //{
            //    Encoding coding = AppConfig.GetEncoding();
            //    return SendRequest(url, new MultipartBodyWriter(requestParams, coding), coding, header);
            //}
            public string SendRequest(string url, IBodyWriter bodyWriter, ICollection<KeyValuePair<string, string>> header)
            {
                Encoding coding = AppConfig.GetEncoding();
                return SendRequest(url, bodyWriter, coding, header);
            }
            public string SendRequest(string url, IBodyWriter bodyWriter)
            {
                Encoding coding = AppConfig.GetEncoding();
                return SendRequest(url, bodyWriter, coding, null);
            }
            public string SendRequest(string url, IBodyWriter bodyWriter, Encoding encoding, ICollection<KeyValuePair<string, string>> DictHeader)
            {
                var request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Accept = "*/*";
                request.KeepAlive = true;
                request.Timeout = 10000;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";

                if (bodyWriter != null)
                {
                    bodyWriter.Writer(request);

                }
                if (DictHeader != null)
                {
                    foreach (var item in DictHeader)
                    {
                        request.Headers.Add(item.Key, item.Value);
                    }
                }
                var response = request.GetResponse();
                using (var s = response.GetResponseStream())
                {
                    var reader = new StreamReader(s, encoding);
                    return reader.ReadToEnd();
                }

            }
        }
        public interface IBodyWriter
        {
            void Writer(HttpWebRequest request);
        }
        public class JsonBodyWriter : IBodyWriter
        {
            private string _content;
            private Encoding _coding;
            public JsonBodyWriter(string content, Encoding coding)
            {
                _content = content;
                _coding = coding;

            }
            public JsonBodyWriter(string content)
            {
                _content = content;
                _coding = AppConfig.GetEncoding();

            }
            public void Writer(HttpWebRequest request)
            {

                request.ContentType = "application/json; charset=utf-8";



                request.Method = "post";
                var requestStream = request.GetRequestStream();
                var tempBuffer = _coding.GetBytes(_content);
                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();

            }
        }
        public class MultipartBodyWriter : IBodyWriter
        {
            private ICollection<KeyValuePair<string, string>> _requestParams;
            private Encoding _coding;
            public MultipartBodyWriter(ICollection<KeyValuePair<string, string>> requestParams, Encoding coding)
            {
                _requestParams = requestParams;
                _coding = coding;

            }
            public MultipartBodyWriter(ICollection<KeyValuePair<string, string>> requestParams)
            {
                _requestParams = requestParams;
                _coding = AppConfig.GetEncoding();

            }
            public void Writer(HttpWebRequest request)
            {

                var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
                var beginBoundary = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                var endBoundary = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                request.ContentType = "multipart/form-data; boundary=" + boundary;

                var strBuf = new StringBuilder();
                if (_requestParams != null)
                {
                    foreach (var key in _requestParams)
                    {
                        strBuf.Append("\r\n--" + boundary + "\r\n");
                        strBuf.Append("Content-Disposition: form-data; name=\"" + key.Key + "\"\r\n\r\n");
                        strBuf.Append(key.Value.ToString());
                    }
                }

                request.Method = "post";
                var requestStream = request.GetRequestStream();
                var tempBuffer = _coding.GetBytes(strBuf.ToString());
                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();

            }
        }
    }

}